package com.RLFZ.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.RLFZ.entity.NocvData;
import com.RLFZ.service.IndexService;
import com.RLFZ.vo.DataView;
import com.RLFZ.vo.NocvDataVo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 86166
 */
@Controller
public class ChinaDataAdminController {
    @Autowired
    private IndexService indexService;
    @RequestMapping("/toChinaManager")
    public String toChinaManger(){
        return "admin/chinadatamanger";
    }

//    public JsonResult findByid(@RequestParam(defaultValue = "1") Integer pageNum,
//                               @RequestParam(defaultValue = "10") Integer pageSize,
//                               @RequestParam(defaultValue = "") String keywords){
//        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
//        if (!StringUtils.isEmpty(keywords)){
//            queryWrapper.like(User::getUsername,keywords).or().like(User::getName,keywords);
//        }
//        IPage pageResult = userService.page(new Page(pageNum, pageSize), queryWrapper);


    @RequestMapping("/listDataByPage")
    @ResponseBody
    public DataView listDataByPage(NocvDataVo nocvDataVo){
        // 创建分页对象
        IPage<NocvData> page=new Page<>(nocvDataVo.getPage(),nocvDataVo.getLimit());
        // 创建模糊查询条件
        QueryWrapper<NocvData> queryWrapper=new QueryWrapper<>();
//        !nocvDataVo.getName().equals(""),
        System.out.println(nocvDataVo.getName());
        Integer maxNocvDate= indexService.max();
//        queryWrapper.like(!(nocvDataVo.getName()==null),"name",nocvDataVo.getName());
        queryWrapper.like(!(nocvDataVo.getName()==null),"name",nocvDataVo.getName()).orderByDesc("id").ge("id",maxNocvDate-34);
        // 疫情确证数据最多的排在最上面
        queryWrapper.orderByDesc("value");
        // 查询数据库
        indexService.page(page,queryWrapper);
        // 返回数据封装
        DataView dataView=new DataView(page.getTotal(),page.getRecords());
        return  dataView;
    }

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping("/china/deleteById")
    @ResponseBody
    public DataView deleteById(Integer id){
        indexService.removeById(id);
        DataView dataView=new DataView();
        dataView.setCode(200);
        dataView.setMsg("删除成功!");
        return dataView;
    }

    /**
     *新增或修改【id】
     * id 有值就是修改每值就是删除
     * @param nocvData
     * @return
     */
    @RequestMapping("/china/addOrUpdateChina")
    @ResponseBody
    public DataView addChina(NocvData nocvData){
        boolean save = indexService.saveOrUpdate(nocvData);
        DataView dataView=new DataView();
        if (save){
            dataView.setCode(200);
            dataView.setMsg("新增中国地图成功!");
            return dataView;
        }
        dataView.setMsg("新增中国地图数据失败！");
        return dataView;
    }

    /**
     * excel 的拖拽或点击上传
     * 1.前端发送一个请求上传文件
     * 2.controller上传文件mutiparFile 参数
     * 3Poi 解析文件，林数据一行一行的全部解析出
     * 4，每一条数据插入数据库
     */
    /*
    @RequestMapping("/excelImportChina")
    @ResponseBody
    public DataView excelImportChina(@RequestParam("file")MultipartFile file) throws Exception{
        DataView dataView=new DataView();

        // 1.文件不能为空
        if (file.isEmpty()){
            dataView.setMsg("文件为空不能上传！");
        }
        // 2.POI获取Excel解析数据
        HSSFWorkbook wb=new HSSFWorkbook(file.getInputStream());
        HSSFSheet sheet=wb.getSheetAt(0);
        //2 定义序列文件接收数据
        List<NocvData> list=new ArrayList<>();
        HSSFRow row = null;
        //4.解析数据
        for (int i=0;i<sheet.getPhysicalNumberOfRows();i++){
           // 4.1定义实体类
            NocvData nocvData=new NocvData();
            // 4.2每一次数据放进实体类中
            row=sheet.getRow(i);
            // 4.3解析数据
            nocvData.setName(row.getCell(0).getStringCellValue());
            nocvData.setValue((int) row.getCell(1).getNumericCellValue());

             //循环插入数据库
            indexService.save(nocvData);

           // 5.添加list集合
            list.add(nocvData);
        }
        // 6.插入数据库
        indexService.saveBatch(list);
        dataView.setCode(200);
        dataView.setMsg("加载文件成功");
        return dataView;
    }
    */

    @RequestMapping(value = "/excelImportChina", method = RequestMethod.POST)
    @ResponseBody
    public DataView uploadExcel(@RequestParam("file") MultipartFile file) {

        DataView dataView = new DataView();
        if (file.isEmpty()) {
            dataView.setMsg("文件为空");
            return dataView;
        }
        try {

            //根据路径获取这个操作excel的实例
            HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet = wb.getSheetAt(0);

            //实体类集合
            List<NocvData> listData = new ArrayList<>();
            HSSFRow row = null;

            //循环sesheet页中数据从第二行开始，第一行是标题
            for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {

                //获取每一行数据
                row = sheet.getRow(i);
                NocvData data = new NocvData();
                data.setName(row.getCell(0).getStringCellValue());
                data.setValue(Integer.valueOf((int) row.getCell(1).getNumericCellValue()));
                listData.add(data);

            }

            //循环展示导入的数据，实际应用中应该校验并存入数据库
            indexService.saveBatch(listData);
            dataView.setCode(200);
            dataView.setMsg("导入成功");
            return dataView;
        } catch (Exception e) {
            e.printStackTrace();
        }
        dataView.setCode(100);
        dataView.setMsg("导入失败");
        return dataView;
    }


    /**
     * Poi
     * 导出excel表格
     */
    @RequestMapping("/excelOutPortChina")
    @ResponseBody
    public void excelOutportChina(HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        List<NocvData> list = indexService.list();
        //1。新建一个excel表
        HSSFWorkbook wb = new HSSFWorkbook();
        //2-创建sheet页,设置sheet页的名字
        HSSFSheet sheet = wb.createSheet("中国数据表");
        //3-创建标题行
        HSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("城市名称");
        titleRow.createCell(1).setCellValue("确诊数量");
        //4-遍历将数据集合将数据放到对应的列中
        for (NocvData data : list){
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
            dataRow.createCell(0).setCellValue(data.getName());
            dataRow.createCell(1).setCellValue(data.getValue());
        }
        // 5.建立输出
        OutputStream os = null;

        try{
            //6-设置Excel的名称

            //6-设置Excel的名称
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setHeader("Content-Disposition", "attachment;filename=" + "中医辨证表.xls");


            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String("中国疫情数据表".getBytes(),"iso-8859-1") + ".xls");
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
        }catch(Exception e){
            e.printStackTrace();

        } finally {
            try {
                if(os != null){
                    os.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
